import track from './track'

export default function blankScreen() {
  const wrapperElements = ['html', 'body', '#monitorWrap', '.container']
  let emptyPoints = 0
  // 白屏点emptyPoints计算
  const isWrapper = (element) => {
    let selector = ''
    if (element.id) {
      selector = `#${element.id}`
    } else if (element.className && typeof element.className === 'string') {
      selector = `.${element.className}`
    } else {
      selector = `${element.nodeName.toLowerCase()}`
    }
    if (wrapperElements.includes(selector)) {
      // 如果最内层的dom元素是wrapperElements这些包裹元素 说明这里没有渲染dom 认为这个点是白屏点
      emptyPoints++
    }
  }
  // 白屏点检测
  window.onload = () => {
    for (let i = 1; i <= 9; i++) {
      //根据实际业务 检测屏幕任意点都可以 这里只检测2*9=18个点 
      const xElements = document.elementFromPoint(window.innerWidth * i / 10, window.innerHeight / 2)
      const yElements = document.elementFromPoint(window.innerWidth / 2, window.innerHeight * i / 10)
      // xElements yElements是对应坐标所在dom的最内层元素
      // 例如坐标点 {x: 100, y:100} 对应的dom是 <div><p><span class="inner">xxx<span></p></div> 那对应的xElements就是<span class="inner">xxx<span>
      isWrapper(xElements)
      isWrapper(yElements)
    }
    // 如果检测18次都是白屏点 说明白屏 上报
    if (emptyPoints >= 18) {
      const log = {
        kind: 'stability',
        type: 'blankScreen',
        emptyPoints: `${emptyPoints} / 18`,
        title: document.title,
        url: window.location.href,
        timestamp: new Date().getTime(),
      }
      console.log('blankScreen', log)
      track.send(log)
    }
  }
}